//
//  HZComposeViewController.swift
//  HansWeibo
//
//  Created by Hans on 16/8/17.
//  Copyright © 2016年 Hans. All rights reserved.
//

import UIKit
import SVProgressHUD

class HZComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    
    // MARK: - 监听事件
    @objc private func cancelAction(){
        // 取消键盘第一响应
        composeTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func sendAction(){
        print("发布按钮")
        // https://api.weibo.com/2/statuses/update.json
        
        composePictureView.imageArray.count == 0 ? updata() : upLoad()
        
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        setupNav()
        // 添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeBottomView)
        composeTextView.addSubview(composePictureView)
        // 添加约束
        composeTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        composeBottomView.snp_makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        composePictureView.snp_makeConstraints { (make) in
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.centerX.equalTo(composeTextView)
        }
        
        
        // 监听底部按钮点击事件Int
        composeBottomView.closure = {[weak self] (type: HZcomposeBottomViewType)->() in
            switch type {
            case .Picture:
                print("")
                self?.selectImage()
            case .Mention:
                print("")
            case .Trend:
                print("")
            case .Emoticon:
                print("")
                self?.switchKeyboard()
            case .Add:
                print("")
            }
        }
        // 配图闭包回调 选择图片
        composePictureView.closure = {[weak self] in
                self?.selectImage()
        }
        // 监听键盘将要改变frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    func keyboardWillChangeFrame(noti:NSNotification){
//        print(noti.userInfo)
        // 动画时长
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
            return
        }
        
        // 判断是否为nil  是否可以转成 NSValue
        guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
            return
        }
        // 获取到CGRect
        let newRect = rect.CGRectValue()
        // 刷新约束
        composeBottomView.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(newRect.origin.y - SCREENH)
        }
        // 设置动画
        UIView.animateWithDuration(duration) {
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    // MARK: - 设置导航
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HZComposeViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HZComposeViewController.sendAction))
        navigationItem.titleView = titleView
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
        let label = UILabel()
        // 用户昵称
        let name = HZUserAccountViewModel.sharedTools.userAccount!.screen_name!
        // 显示内容
        let str = "发微博\n\(name)"
        // 初始化富文本
        let arrt = NSMutableAttributedString(string: str)
        // 获取范围
        let range = (str as NSString).rangeOfString(name)
        // 设置富文本
        arrt.addAttributes([
            // 字体颜色
            NSForegroundColorAttributeName:AppTheneColor,
            // 字体颜色
            NSFontAttributeName: UIFont.systemFontOfSize(12)
            // range 范围
            ], range: range)
        label.numberOfLines = 0
        // 富文本设置 label 的text
        label.attributedText = arrt
        label.sizeToFit()
        label.textAlignment = .Center
        return label
    }()
    // 自定义textView
    private lazy var composeTextView :HZComposeTextView = {
        let view = HZComposeTextView()
        view.delegate = self
        // 设置字体大小
        view.font = UIFont.systemFontOfSize(15)
        // 设置占位文字
        view.placeholder = "mengmengmengmeng"
        // 允许上下滚动
        view.alwaysBounceVertical = true
        return view
    }()
    // 自定义底部视图
    private lazy var composeBottomView: HZcomposeBottomView = HZcomposeBottomView()
    // 配图
    private lazy var composePictureView :HZComposePictureView = HZComposePictureView()
    // 自定义表情键盘
    private lazy var emoticonKetboardView :HZEmoticonKetboardView = HZEmoticonKetboardView(frame: CGRect(x: 0, y: 0, width: SCREENW, height: 216))
    
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    
}

// MARK: - 发布微博
extension HZComposeViewController {
    // 发布文字微博
    func updata(){
        
        HZNetworkTools.sharedTools.composeUpdata(composeTextView.text, success: { (response) in
            SVProgressHUD.showSuccessWithStatus("发布成功")
        NSNotificationCenter.defaultCenter().postNotificationName("backReload", object: nil)
            
            self.cancelAction()
            
            }) { (error) in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
    
    // 发布图片微博
    func upLoad(){

        HZNetworkTools.sharedTools.composeUpload(composeTextView.text, images: composePictureView.imageArray, success: { (response) in
            SVProgressHUD.showSuccessWithStatus("发布成功")
        NSNotificationCenter.defaultCenter().postNotificationName("backReload", object: nil)
            
            self.cancelAction()
            
            }) { (error) in
                SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
}
//         请求的url
//        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
//         请求参数
//        let parmas = ["access_token":HZUserAccountViewModel.sharedTools.access_token!,
//                      "status":composeTextView.text]
//        
//        HZNetworkTools.sharedTools.POST(urlString, parameters: parmas, constructingBodyWithBlock: { (formdata) in
//             把上传的文件拼接在表单后面  application/octet-stream
//             上传单张图片
//            let data = UIImagePNGRepresentation(self.composePictureView.imageArray.first!)!
//            formdata.appendPartWithFileData(data, name: "pic", fileName: "qwqwq", mimeType: "application/octet-stream")
//            
//            // 上传多张图片
//            for (i,image) in self.composePictureView.imageArray.enumerate() {
//                let data = UIImagePNGRepresentation(image)!
//
//                formdata.appendPartWithFileData(data, name: "pic\(i+1)", fileName: "qwqwq", mimeType: "application/octet-stream")
//            }
//            }, progress: nil, success: { (_, response) in
//                SVProgressHUD.showSuccessWithStatus("发布成功")
//            }) { (_, error) in
//                SVProgressHUD.showErrorWithStatus("发布失败")
//        }
//        




// MARK: - UITextViewDelegate
extension HZComposeViewController: UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        self.composeTextView.placeholder = nil
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 键盘第一响应
        self.composeTextView.resignFirstResponder()
    }
}
// MARK: - 处理底部图片按钮的事件
extension HZComposeViewController {
    // 选择图片
    func selectImage(){
        let pickerVc = UIImagePickerController()
        pickerVc.delegate = self
        self.presentViewController(pickerVc, animated: true, completion: nil)
    }
    // 切换键盘
    func switchKeyboard(){
        // 代表显示的是系统键盘
        if composeTextView.inputView == nil {
            composeTextView.inputView = emoticonKetboardView
            composeBottomView.isEmoticon = true
        }else{
            // 代表自定义键盘
            composeTextView.inputView = nil
            composeBottomView.isEmoticon = false
        }
        // 刷新
        composeTextView.reloadInputViews()
        // 成为第一响应者
        composeTextView.becomeFirstResponder()
    }
    
}
extension HZComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
//        print(info)
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        // 添加图片
        composePictureView.addImage(UIImage.dealImageScale(image, width: 600))
        // 关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
//    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
//        <#code#>
//    }
    // 已经废弃
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        <#code#>
//    }
    
}



